export const custom = {
  loading: true,
  auth: true,
  toast: false,
  catch: true,
  tokenPrefix: "Bearer",
  tokenNeedPrefix: false,
  /** post url链接挂载params参数 */
  postMountParams: false,
  /** token过期是否重新登录 */
  refreshToken: true,
};

/**
 * 参数处理
 * @param {*} params  参数
 */
export function tansParams(params) {
  let result = "";
  for (const propName of Object.keys(params)) {
    const value = params[propName];
    var part = encodeURIComponent(propName) + "=";
    if (value !== null && value !== "" && typeof value !== "undefined") {
      if (typeof value === "object") {
        for (const key of Object.keys(value)) {
          if (
            value[key] !== null &&
            value[key] !== "" &&
            typeof value[key] !== "undefined"
          ) {
            let params = propName + "[" + key + "]";
            var subPart = encodeURIComponent(params) + "=";
            result += subPart + encodeURIComponent(value[key]) + "&";
          }
        }
      } else {
        result += part + encodeURIComponent(value) + "&";
      }
    }
  }
  if (result.endsWith("&")) result = result.slice(0, result.length - 1);
  return result;
}

export const handleParams = (config = {}) => {
  return uni.$u.deepMerge(
    {
      custom: custom,
    },
    config
  );
};

export const formatGetParams = ({ config, params }) => {
  const data = {};
  Object.keys(params).forEach((key) => {
    if (optionIsNotNull(params[key])) {
      data[key] = params[key];
    }
  });
  return {
    ...handleParams(config),
    data,
  };
};

export const optionIsNotNull = (val) => {
  return val === 0 || !!val;
};

export const formatToken = (token, custom = custom) => {
  if (!token) return token;
  const prefix = custom.tokenPrefix ?? "Bearer";
  let result = token;
  if (custom.auth) {
    const has = token.includes(prefix);
    if (custom.tokenNeedPrefix && !has) result = `${prefix} ${token}`;
  }
  return result;
};

/**
 * 请求路由白名单
 */
export const whiteList = [""];

export const toRefreshToken = async () => {};
